/**
 * ReportGear(2011)
 */
package com.reportgear.report.model.auxiliary;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.reportgear.report.util.ReportUtils;

/**
 * 行列对象
 * 
 * @version 1.0 2011-3-13
 * @author <a herf="lexloo@gmail.com">lexloo</a>
 * @since Report 1.0
 */
public class ColumnRow {

	private static final Logger logger = LoggerFactory.getLogger(ColumnRow.class.getName());
	// 列
	private int column;
	// 行
	private int row;

	private ColumnRow(int column, int row) {
		this.column = column;
		this.row = row;
	}

	/**
	 * 根据行列获取ColumnRow对象
	 * 
	 * @param column
	 * @param row
	 * @return ColumnRow对象
	 */
	public static ColumnRow valueOf(int column, int row) {
		if (column >= 0 && column < 5 && row >= 0 && row < 10) {
			return ColumnRowCache.cache[column][row];
		} else {
			return new ColumnRow(column, row);
		}
	}

	/**
	 * 根据字符串如:A1获取ColumnRow对象
	 * 
	 * @param columnRowStr
	 *            字符串
	 * @return ColumnRow对象
	 */
	public static ColumnRow valueOf(String columnRowStr) {
		ColumnRow columnRow = valueOf(-1, -1);
		if (columnRowStr == null) {
			return columnRow;
		}
		columnRowStr = columnRowStr.trim();
		if (!columnRowStr.matches("[a-zA-Z]+\\d+")) {
			return columnRow;
		}
		try {
			columnRow = valueOf(ReportUtils.convertABCToInt(columnRowStr.replaceAll("\\d", "")) - 1, Integer
					.parseInt(columnRowStr.replaceAll("[a-zA-Z]", "")) - 1);
		} catch (NumberFormatException ex) {
			logger.warn(ex.getMessage());
		}
		return columnRow;
	}

	public int getColumn() {
		return column;
	}

	public int getRow() {
		return row;
	}

	@Override
	public String toString() {
		return ReportUtils.convertIntToABC(column + 1) + (row + 1);
	}

	@Override
	public int hashCode() {
		int result = 17;
		result = 31 * result + column;
		result = 31 * result + row;

		return result;
	}

	@Override
	public boolean equals(Object o) {
		if (o == null || !(o instanceof ColumnRow)) {
			return false;
		} else {
			ColumnRow columnrow = (ColumnRow) o;
			return getColumn() == columnrow.getColumn() && getRow() == columnrow.getRow();
		}
	}

	// 缓存
	private static class ColumnRowCache {

		static final ColumnRow cache[][];

		static {
			cache = new ColumnRow[5][10];
			for (int i = 0; i < cache.length; i++) {
				int j = 0;
				for (int k = cache[i].length; j < k; j++) {
					cache[i][j] = new ColumnRow(i, j);
				}
			}
		}

		private ColumnRowCache() {
		}
	}
}
